<template>
    <!-- 出差申请界面 -->
    <div style="padding: 10px;">
        <el-row :gutter="24">
            <el-col :span="2">
                <div class="grid-content ep-bg-purple"><el-button type="primary" size="default" style="width: 100px;"
                        @click="add">提交申请</el-button>

                </div>
            </el-col>

            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>

            <el-col :span="12">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>

            <el-col :span="4">
                <div class="grid-content ep-bg-purple-light">
                    <!-- 将搜索输入框与 searchKeyword 响应式变量进行双向绑定 -->
                    <el-input style="width: 180px" size="default" placeholder="搜索数据" v-model="businessTripNum"
                        @blur="loadBusinessTrip" @keyup.enter="loadBusinessTrip">
                        <template #prefix>
                            <el-icon class="el-input__icon">
                                <search />
                            </el-icon>
                        </template>
                    </el-input>
                </div>
            </el-col>

            <!-- <el-col :span="1">
                <div class="grid-content ep-bg-purple-light">
                    <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click="dialog = true"><el-icon>
                                <Filter />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>

            <el-col :span="1">
                <div class="grid-content ep-bg-purple-light"> <a-tooltip content="排序" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click=""><el-icon>
                                <Sort />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col> -->


            <el-col :span="2">
                <div class="grid-content ep-bg-purple-light"><a-tooltip content="刷新" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click="refresh"><el-icon>
                                <Refresh />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>
            <!--  -->
        </el-row>

        <el-row :gutter="24">
            <el-col :span="24">
                <el-table :data="businessTripPage.records" show-overflow-tooltip style="height: 800px;" scrollbar-always-on
                    @row-click="handleRowClick">
                    <el-table-column v-for="col in businessTrip_columns" :prop="col.id" :label="col.label" :width="col.width">
                    </el-table-column>
                </el-table>

                <el-pagination @current-change="loadBusinessTrip" v-model:currentPage="businessTripPage.current"
                    :page-sizes="[2, 4, 6, 8, 10]" :page-size="businessTripPage.size" :total="businessTripPage.total" background>
                </el-pagination>
            </el-col>
        </el-row>
    </div>

    <!--筛选  -->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
        <div class="demo-drawer__content">
            <el-form :model="form" style="height: 600px;">
                <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
                    <template #label="{ label, value }">
                        <span style="font-weight: bold">{{ label }}</span>
                    </template>
                    <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onClick">
                    {{ loading ? '提交中 ...' : '提交' }}
                </el-button>
            </div>
        </div>
    </el-drawer>

    <!--添加  -->
    <el-dialog align-center destroy-on-close title="出差申请" v-model="AddDisplay" width="780px">
        <businessTrip @ref-table="refTable"></businessTrip>
    </el-dialog>

    <!-- 详情页面 -->
    <el-dialog align-center destroy-on-close :title="user.employeeName+'-'+user.department.deptName" v-model="dialogVisible" width="780px">
        <businessTripDetails :businessTripDetails="selectedRow"></businessTripDetails>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';  // 引入 computed 用于创建计算属性
import request from '@/api/request';
import businessTrip from './businessTrip.vue';
import businessTripDetails from './businessTripDetails.vue';
const isVisible = ref(false) // 详情显示
const loading = ref(false) //抽屉加载
const dialog = ref(false); //抽屉

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');

const businessTripNum = ref('')

// 添加搜索关键词响应式变量，用于存储用户输入的搜索内容
const searchKeyword = ref('')

const dialogVisible = ref(false)
const selectedRow = ref({})

const handleRowClick = (row, event, column) => {
    selectedRow.value = row
    dialogVisible.value = true
}

// columns : 表头
const businessTrip_columns = ref([
    { id: 'tripId', label: '出差单号', width: '200' },
    { id: 'applicationDate', label: '申请日期', width: '200' },
    { id: 'destination', label: '出差目的地', width: '200' },
    { id: 'startDate', label: '出差开始日期', width: '200' },
    { id: 'endDate', label: '出差结束日期', width: '200' },
    { id: 'predictDate', label: '预计出差天数', width: '200' },
    { id: 'reason', label: '出差事由', width: '200' },
    { id: 'createdAt', label: '提交时间', width: '200' },
    { id: 'updatedAt', label: '更新时间', width: '200' },
])
// 数据
const businessTripPage = ref({
    current: 1,
    size: 3,
    total: 0,
    records: []
})

// 计算出差天数的函数
const calculateTripDays = (startDate, endDate) => {
    if (!startDate || !endDate) return '';
    
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    // 检查日期有效性
    if (isNaN(start.getTime()) || isNaN(end.getTime()) || start > end) {
        return '';
    }
    
    // 计算时间差（毫秒）
    const timeDifference = end.getTime() - start.getTime();
    
    // 转换为天数，包含起始日期
    const daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24)) + 1;
    
    return daysDifference;
}

// 带有计算出差天数的业务 trip 数据
const businessTripPageWithCalculatedDays = computed(() => {
    const recordsWithDays = businessTripPage.value.records.map(record => {
        // 如果记录中没有 predictDate，则计算
        if (!record.predictDate) {
            return {
                ...record,
                predictDate: calculateTripDays(record.startDate, record.endDate)
            };
        }
        return record;
    });
    
    return {
        ...businessTripPage.value,
        records: recordsWithDays
    };
});

//刷新
const refresh = () => {
    request({
        url: "/businessTrip/page",
        method: "get",
        params: {
            current: 1,
            size: businessTripPage.value.size,
            userId: user.employeeId
        }
    }).then(resp => {
        businessTripPage.value = resp.data;
        businessTripNum.value = '';
        console.log(resp.data);
    });
};

let loadBusinessTrip = () => {
    request({
        url: "/businessTrip/page",
        method: "get",
        params: {
            current: businessTripPage.value.current,
            size: businessTripPage.value.size,
            userId: user.employeeId,
            applicationDate: businessTripNum.value
        }
    }).then(resp => {
        businessTripPage.value = resp.data;
        console.log(resp.data);
        
        // 确保表格数据显示出差天数
        businessTripPage.value.records = businessTripPage.value.records.map(record => {
            if (!record.predictDate && record.startDate && record.endDate) {
                return {
                    ...record,
                    predictDate: calculateTripDays(record.startDate, record.endDate)
                };
            }
            return record;
        });
    });
};

let refTable = () => {
    AddDisplay.value = false;
    loadBusinessTrip();
}

// 根据状态返回 Tag 类型
const getTagType = (status) => {
    switch (status) {
        case "上午签到":
            return "success";
        case "下午签退":
            return "primary";
        default:
            return "default";
    }
};

const getTagType2 = (status) => {
    switch (status) {
        case "同意":
            return "success";
        case "不同意":
            return "danger";
        default:
            return "default";
    }
};

// 将搜索关键词转换为小写以实现不区分大小写的搜索
const keyword = searchKeyword.value.toLowerCase()

const form = ref();
const Screening = ref('') //筛选
const FilterData = ref([ //筛选数据
    { value: '全部', label: '全部' },
    { value: '待面试', label: '待面试' },
    { value: '待入职', label: '待入职' },
])
const onClick = () => {//抽屉提交
    loading.value = true
    setTimeout(() => {
        loading.value = false
        dialog.value = false
    }, 400)
}
//抽屉提交取消
const cancelForm = () => {
    loading.value = false
    dialog.value = false
}
// 获取当前数据
const handleClick = (row) => {
    console.log(row)
    isVisible.value = true
}
const AddDisplay = ref(false) // 添加显示
const Initiate = () => { //发起面试关闭
    AddDisplay.value = false
}
const add = () => { //添加
    AddDisplay.value = true

}

loadBusinessTrip()
</script>

<style scoped></style>